package efuliBusiness;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import efuliBusiness.efuliApi.Member;
import efuliBusiness.efuliApi.Recharge_arr;
import efuliBusiness.efuliApi.Welfarepoint;
import efuliBusiness.efuliApi.WelfarepointSetData;
import impl.TestServerBusinessImpl;
import models.MyConfig;
import models.Page;
import models.ReturnJson;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Objects;

/**
 * Created by yangxianming on 2018/5/11.
 */
public class CorpMng implements TestServerBusinessImpl {
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        ReturnJson returnJson = new ReturnJson();

        //读取请求json
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String requestInfo = "";

        try {
            inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null)
                requestInfo = requestInfo + line;

            //解析json对象
            JSONObject apiJson = JSON.parseObject(requestInfo);
            System.out.println(apiJson);

            Welfarepoint welfarepoint = new Welfarepoint(apiJson.getString("env"));
            WelfarepointSetData wsd = new WelfarepointSetData();
            String request_id = String.valueOf(System.currentTimeMillis());

            //获取企业列表
            if (Objects.equals(apiJson.getString("action"), "getCorpList")){
                String sql = "SELECT corp_name,corp_id,is_open_flpay,withhold_status,withhold_model,account_balance,gifting_status,rmb_point_ratio  FROM wf_corporation WHERE app_id='welfarepoint12345678901234567890' ORDER BY create_time DESC";

                JSONArray r = welfarepoint.efuli_data_query(wsd.efuli_data_query(request_id, sql)).getJSONArray("return_data");

//                String partOfMemberSql = "SELECT ";
//                String partOfDiscountSql = "SELECT ";

                JSONArray returnDataArr = new JSONArray();
                for (int i = 0; i < r.size(); i++){
                    JSONObject returnDataOne = new JSONObject();
                    JSONObject aCop = r.getJSONObject(i);
                    String corp_id = aCop.getString("corp_id");
                    String corp_name = aCop.getString("corp_name");
                    String is_open_flpay = aCop.getString("is_open_flpay");
                    String withhold_status = aCop.getString("withhold_status");
                    String withhold_model = aCop.getString("withhold_model");
                    String account_balance = aCop.getString("account_balance");
                    String gifting_status = aCop.getString("gifting_status");
                    String rmb_point_ratio = aCop.getString("rmb_point_ratio");
                    //查询员工总数
//                    String tail = String.format("%02d", Math.abs(corp_id.hashCode() % 100));
//                    partOfMemberSql = partOfMemberSql + "(SELECT count(*) FROM corp_user_0" + tail + " WHERE corp_id='" + corp_id + "') AS c" + i + ",";

                    //查询折扣商家总数
//                    partOfDiscountSql = partOfDiscountSql + "(SELECT COUNT(*) FROM efulicore_merchant.merchant_discount WHERE corp_id='" + corp_id + "' AND `status`=2) AS c" + i + ",";

                    //塞数据
                    returnDataOne.put("companyName", corp_name);
                    returnDataOne.put("corpId", corp_id);
                    returnDataOne.put("is_open_flpay", is_open_flpay);
                    returnDataOne.put("withhold_status", withhold_status);
                    returnDataOne.put("withhold_model", withhold_model);
                    returnDataOne.put("account_balance", account_balance);
                    returnDataOne.put("gifting_status", gifting_status);
                    returnDataOne.put("rmb_point_ratio", rmb_point_ratio);
                    returnDataArr.add(returnDataOne);
                }
                //查询并塞数据，关联数据
//                partOfMemberSql = partOfMemberSql.substring(0, partOfMemberSql.length()-1);
//                partOfDiscountSql = partOfDiscountSql.substring(0, partOfDiscountSql.length()-1);
//                JSONObject memberOBJ = welfarepoint.efuli_data_query(wsd.efuli_data_query(request_id, partOfMemberSql)).getJSONArray("return_data").getJSONObject(0);
//                JSONObject discountOBJ = welfarepoint.efuli_data_query(wsd.efuli_data_query(request_id, partOfDiscountSql)).getJSONArray("return_data").getJSONObject(0);
                for (int i = 0; i < returnDataArr.size(); i++){
                    returnDataArr.getJSONObject(i).put("coreUserCount", "--");
                    returnDataArr.getJSONObject(i).put("compantMerchantDiscount", "--");
                }

                returnJson.setResult(returnDataArr);
                return returnJson.toString();
            }

            //创建企业
            if (Objects.equals(apiJson.getString("action"), "corpCreate")){
                JSONObject createReturn = welfarepoint.efuli_welfarepoint_corp_create(wsd.efuli_welfarepoint_corp_create(
                        request_id,
                        apiJson.getString("corpName"),
                        apiJson.getString("corpCity"),
                        apiJson.getString("corpMail"),
                        apiJson.getString("corpType"),
                        apiJson.getString("corpLogo"),
                        apiJson.getString("corpAddress"),
                        apiJson.getString("corpMobile"),
                        apiJson.getString("point_name"),
                        apiJson.getString("rmb_point_ratio")));
                if (Objects.equals(createReturn.getString("return_code"), "00")){
                    returnJson.setResult(createReturn);
                }else {
                    returnJson.setApiStatus(0);
                    returnJson.setErrorMsg("创建企业失败了！");
                }
                return returnJson.toString();
            }
            //添加企业员工
            if (Objects.equals(apiJson.getString("action"), "empCreate")){
                JSONObject menber = apiJson.getJSONArray("members").getJSONObject(0);    //暂时一次添加一个人

                ArrayList<Member> members = new ArrayList<Member>();
                members.add(new Member(
                        menber.getString("cert_type"),
                        menber.getString("cert_no"),
                        menber.getString("name"),
                        menber.getString("cardno"),
                        menber.getString("mobile"),
                        menber.getString("department")));
                JSONObject createReturn = welfarepoint.efuli_welfarepoint_member_create(wsd.efuli_welfarepoint_member_create(
                        request_id,
                        apiJson.getString("corpCode"),
                        members
                        ));
                if (Objects.equals(createReturn.getString("return_code"), "00")){
                    returnJson.setResult(createReturn);
                }else {
                    returnJson.setApiStatus(0);
                    returnJson.setErrorMsg("创建员工失败了！");
                }
                return returnJson.toString();
            }


            //获取企业会员列表
            //获取企业会员分页数据(limit a,b) a为起始下标  b为包括起始下标在内向后取几行
            final Integer everyPage = 19;   //企业员工列表每页几行 25个
            if (Objects.equals(apiJson.getString("action"), "getCorpMemList")){
                String corp_id = apiJson.getString("corp_id");
                String real_name = apiJson.getString("real_name");
                String where_real_name = "";
                if (!Objects.equals("", real_name) && !Objects.equals(null, real_name)){
                    where_real_name = " AND real_name LIKE \"%" + real_name + "%\"";
                }
                int toPage = Integer.valueOf(apiJson.getString("toPage")) - 1;  //前端需要跳转第几页
                int nowPageFrom = toPage * everyPage;                                        //通过每页个数，算出数据库起始行号
                String tail = String.format("%02d", Math.abs(corp_id.hashCode() % 100));
                String sql = "SELECT real_name,job_no,account_balance,ali_user_id FROM corp_user_0" + tail + " WHERE corp_id='" + corp_id + "'" + where_real_name + " ORDER BY create_time DESC limit " + nowPageFrom + ", " + everyPage;
                System.out.println(sql);
                returnJson.setResult(welfarepoint.efuli_data_query(wsd.efuli_data_query(request_id, sql)).getJSONArray("return_data"));
                return returnJson.toString();
            }
            //获取企业会员总页码数
            if (Objects.equals(apiJson.getString("action"), "getCorpMemCountPage")){
                String corp_id = apiJson.getString("corp_id");
                String corpUserTail = String.format("%02d", Math.abs(corp_id.hashCode() % 100));
                String sql = "SELECT SUM(1) FROM corp_user_0" + corpUserTail + " WHERE corp_id='" + corp_id + "'";
                Integer count;
                JSONObject js = welfarepoint.efuli_data_query(wsd.efuli_data_query(request_id, sql)).getJSONArray("return_data").getJSONObject(0);
                if (js.containsKey("sum(1)")){
                    count  = Integer.valueOf(js.getString("sum(1)"));
                }else {
                    //如果没有sum(1) 说明没有数据
                    count = 0;
                }
                returnJson.setResult(Page.getPageCount(count, everyPage));
                return returnJson.toString();
            }
            //获取企业会员分页数据(limit a,b) a为起始下标  b为包括起始下标在内向后取几行
//            if (Objects.equals(apiJson.getString("action"), "getCorpMemStepPage")){
//                String corp_id = apiJson.getString("corp_id");
//                String corpUserTail = String.format("%02d", Math.abs(corp_id.hashCode() % 100));
//                String sql = "SELECT SUM(1) FROM corp_user_0" + corpUserTail + " WHERE corp_id='" + corp_id + "'";
//
//            }

            //是否开通福利金买单
            if (Objects.equals(apiJson.getString("action"), "isOpenFLpay")){
                String operate = apiJson.getString("operate");
                String corp_id = apiJson.getString("corp_id");
//                String sql = "UPDATE efulipoint.wf_corporation SET is_open_flpay='" + operate + "' WHERE corp_id='704adc60a25d45ab83aefbcacee01350'";
                String sql = "UPDATE efulipoint.wf_corporation SET is_open_flpay='" + operate + "' WHERE corp_id='" + corp_id + "'";
                //每次取token
                String token = welfarepoint.efuli_data_update1(wsd.efuli_data_update1(request_id)).getString("return_data");
                String return_desc = welfarepoint.efuli_data_update2(wsd.efuli_data_update2(request_id, sql, token)).getString("return_desc");

                returnJson.setResult(return_desc);
                return returnJson.toString();
            }
            //是否开通代扣
            if (Objects.equals(apiJson.getString("action"), "isOpenWithhold")){
                String operate = apiJson.getString("operate");
                String corp_id = apiJson.getString("corp_id");
                String sql = "UPDATE efulipoint.wf_corporation SET withhold_status='" + operate + "' WHERE corp_id='" + corp_id + "'";
                //每次取token
                String token = welfarepoint.efuli_data_update1(wsd.efuli_data_update1(request_id)).getString("return_data");
                String return_desc = welfarepoint.efuli_data_update2(wsd.efuli_data_update2(request_id, sql, token)).getString("return_desc");

                returnJson.setResult(return_desc);
                return returnJson.toString();
            }

            //是否开通转赠{"operate":"Y"/"N","corp_id":""}
            if (Objects.equals(apiJson.getString("action"), "isOpenGifting")){
                String operate = apiJson.getString("operate");
                String corp_id = apiJson.getString("corp_id");
//                String sql = "UPDATE efulipoint.wf_corporation SET gifting_status='" + operate + "' WHERE corp_id='" + corp_id + "'";
                String sql = "UPDATE efulipoint.wf_corporation SET gifting_status='" + operate + "' WHERE corp_id='49219587ecbc4c76a9ab7e138d4451cd'";
                //每次取token
                String token = welfarepoint.efuli_data_update1(wsd.efuli_data_update1(request_id)).getString("return_data");
                String return_desc = welfarepoint.efuli_data_update2(wsd.efuli_data_update2(request_id, sql, token)).getString("return_desc");

                returnJson.setResult(return_desc);
                return returnJson.toString();
            }

            //设置rmb_point_ratio 福利金与rmb的对边比率值
            if (Objects.equals(apiJson.getString("action"), "setRmbpointratio")){
                String corp_id = apiJson.getString("corp_id");
                String rmb_point_ratio = apiJson.getString("rmb_point_ratio");
                String sql = "UPDATE efulipoint.wf_corporation SET rmb_point_ratio='" + rmb_point_ratio + "' WHERE corp_id='" + corp_id + "'";
                //每次取token
                String token = welfarepoint.efuli_data_update1(wsd.efuli_data_update1(request_id)).getString("return_data");
                String return_desc = welfarepoint.efuli_data_update2(wsd.efuli_data_update2(request_id, sql, token)).getString("return_desc");

                returnJson.setResult(return_desc);
                return returnJson.toString();
            }

            //代扣方式 1.发放扣  2.消费扣
            if (Objects.equals(apiJson.getString("action"), "withhold_model")){
                String operate = apiJson.getString("operate");
                String corp_id = apiJson.getString("corp_id");
                String sql = "UPDATE efulipoint.wf_corporation SET withhold_model='" + operate + "' WHERE corp_id='" + corp_id + "'";
                //每次取token
                String token = welfarepoint.efuli_data_update1(wsd.efuli_data_update1(request_id)).getString("return_data");
                String return_desc = welfarepoint.efuli_data_update2(wsd.efuli_data_update2(request_id, sql, token)).getString("return_desc");

                returnJson.setResult(return_desc);
                return returnJson.toString();
            }
            //企业充值
            if (Objects.equals(apiJson.getString("action"), "corpRecharge")){
                String corp_id = apiJson.getString("corp_id");
                String amount = apiJson.getString("amount");
                JSONObject r = welfarepoint.efuli_welfarepoint_corp_recharge(wsd.efuli_welfarepoint_corp_recharge(request_id, corp_id, amount));
                if (Objects.equals(r.getString("return_code"), "00")){
                    returnJson.setResult(r);
                }else {
                    returnJson.setApiStatus(0);
                    returnJson.setErrorMsg("充值失败");
                }
                return returnJson.toString();
            }
            //企业员工充值
            if (Objects.equals(apiJson.getString("action"), "recharge")){
                String corp_id = apiJson.getString("corp_id");
                String job_no = apiJson.getString("job_no");
                String rechargeNumber = apiJson.getString("rechargeNumber");
                ArrayList<Recharge_arr> recharge_arrs = new ArrayList<Recharge_arr>();
                recharge_arrs.add(new Recharge_arr(job_no, rechargeNumber));
                JSONObject r = welfarepoint.efuli_welfarepoint_recharge(wsd.efuli_welfarepoint_recharge(request_id, corp_id, "01", recharge_arrs));
                if (Objects.equals(r.getString("return_code"), "00")){
                    returnJson.setResult(r);
                }else {
                    returnJson.setApiStatus(0);
                    returnJson.setErrorMsg("充值失败");
                }
                return returnJson.toString();
            }

        }catch (Exception e){
            //请求流如果出现异常的时候
            e.printStackTrace();
            returnJson.setApiStatus(0);
            returnJson.setErrorMsg(e.getMessage());
            return returnJson.toString();
        }
        returnJson.setApiStatus(0);
        returnJson.setErrorMsg("action的参数没有对应的操作");
        return returnJson.toString();
    }
}
